/*******************************************************************************************************/
/****************************************常用自定义辅助工具函数库***************************************/
/*******************************************************************************************************/
var ua = window.navigator.userAgent.toLowerCase();
export default{
	dialogMsg : function(obj,msg){
		obj.$broadcast('closeDialog');
		obj.isShow = true;
		obj.dialogMsg = msg;
	},
	baudu_htm:function(){
		window._hmt.push(['_trackPageview', window.location.pathname+window.location.hash]);
	},
	setTitle:function(t){
		var _self=this;
		setTimeout(function(){
		    //利用iframe的onload事件刷新页面
		    document.title = t;
		    var iframe = document.createElement('iframe');
		    iframe.style.visibility = 'hidden';
		    iframe.style.width = '1px';
		    iframe.style.height = '1px';
		    iframe.onload = function () {
		        setTimeout(function () {
		            document.body.removeChild(iframe);
		        }, 0);
		    };
		    document.body.appendChild(iframe);
		},0);
	},
	formatImgPath:function(data,userPic,size){
        var arr=[],size=size?size:'55x55';
        if( Object.prototype.toString.call(data) === '[object Array]' ){
        	 $.each(data,function(id,obj){
	            var upc=obj[userPic];
	            if(upc){
	                var front_str=upc.substring(0,upc.lastIndexOf('.')),
	                end_str=upc.substr(upc.lastIndexOf('.'));
	                obj[userPic]=front_str+'_'+size+end_str;
	            }
	            arr.push(obj);
	        });
	        data=arr;
        }else{
        	var upc=data[userPic];
        	if( upc ){
        		var front_str=upc.substring(0,upc.lastIndexOf('.')),
	        	end_str=upc.substr(upc.lastIndexOf('.'));
	        	data[userPic] = front_str+'_'+size+end_str;
        	}
        }
	},
	initDefaultImg:function(objs,url){
        objs.on('error',function(ev){
            var e = ev || window.event || arguments.callee.caller.arguments[0];
            e.srcElement.src=url;
            $(this).off('error');
        });
	},
	getQueryString:function(name)
	{
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = window.location.search.substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	},
	ck_device:function(){
	    var browser = {
	       versions: function () {
	           var u = navigator.userAgent, app = navigator.appVersion;
	           return {         //移动终端浏览器版本信息
	               trident: u.indexOf('Trident') > -1, //IE内核
	               presto: u.indexOf('Presto') > -1, //opera内核
	               webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	               gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
	               mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
	               ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	               android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
	               iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
	               iPad: u.indexOf('iPad') > -1, //是否iPad
	               webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
	           };
	       }(),
	       language: (navigator.browserLanguage || navigator.language).toLowerCase()
	    },result={platform:'',appname:''};
	    if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面
	           if(browser.versions.ios) {
                   //是否在IOS浏览器打开
	        		result.platform = 'IOS';
	           } 
	           if(browser.versions.android){
                   //是否在安卓浏览器打开
	        		result.platform = 'Android';
	           }
	           if (ua.match(/MicroMessenger/i) == "micromessenger") {
                   //在微信中打开
	        		result.appname = 'WX';
	           }
	           if (ua.match(/WeiBo/i) == "weibo") {
                   //在新浪微博客户端打开
	        		result.appname = 'WB';
	           }
	           if (ua.match(/QQ/i) == "qq") {
                   //在QQ空间打开
	        		result.appname = 'QQ';
	           }
	    } else {
	           //否则就是PC浏览器打开
        		result.platform = 'PC';
	    }
	    return result;
	},
	paramcompare:function(arr,callback){
		var result={},temp={};
		for(var i=0;i<arr.length;i++){
			if(temp[arr[i].name]){
				var key=arr[i].name,oldvalue=result[key],newvalue=arr[i].value,temp_arr=[];
				if(oldvalue.constructor == Array){
					result[key]=oldvalue.concat(newvalue);
				}else{
					temp_arr.push(oldvalue);
					temp_arr.push(newvalue);
					result[key]= temp_arr;
				}
			}else{
				result[arr[i].name]=arr[i].value;
				temp[arr[i].name]=true;
			}
		}
		if(callback instanceof Function) callback(result);
		return result;
	},
	stopBubble:function(ev){
		var e = ev || window.event || arguments.callee.caller.arguments[0];
	   //一般用在鼠标或键盘事件上
	   if(e && e.stopPropagation){
		   //W3C取消冒泡事件
		   e.stopPropagation();
	   }else{
		   //IE取消冒泡事件
		   window.event.cancelBubble = true;
	   }
	},
	stopDefault:function(ev){
		var e = ev || window.event || arguments.callee.caller.arguments[0];
	    //阻止默认浏览器动作(W3C) 
	    if ( e && e.preventDefault ) 
	        e.preventDefault(); 
	    //IE中阻止函数器默认动作的方式 
	    else 
	        window.event.returnValue = false;
	},
	dateFormat: function (date, format) {
        format = format || 'yyyy-MM-dd hh:mm:ss';
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },
	setCookie : function(key,value){
		$.cookie(key,value,{path:"/",domain:".jiuxiulvxing.com"});
	},
    getCookie:function(key){
        var arr,reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
        	return unescape(arr[2]);
        else
        	return null;
    },
    delCookie:function(key){
		$.cookie(key,"",{path:"/",domain:".jiuxiulvxing.com"});
    },
	openAppShare : function(shareTitle,shareContent,shareImageUrl,shareWebPage,shareWay){
		shareTitle = encodeURIComponent(shareTitle);
		shareContent = encodeURIComponent(shareContent);
		shareImageUrl = encodeURIComponent(shareImageUrl);
		shareWebPage = encodeURIComponent(shareWebPage);
		if(!shareWay || shareWay == null || shareWay == ""){
			shareWay = "-1";
		}
		if(shareWay != "-1" //全部 
			&& shareWay != "1" //微信
			&& shareWay != "2" //微信朋友圈
			&& shareWay != "3" //QQ
			&& shareWay != "4" //Weibo
			&& shareWay != "5" //达人圈
			){
			alert("暂不支持分享类型");
			return false;
		}
		window.location.href ='yimay://app?content={"TYPE":"JIUXIU","OPERATION":"WEB_SHARE","DATA":{"shareTitle":"'+shareTitle+
		'","shareContent":"'+shareContent+'","shareImageUrl":"'+shareImageUrl+'","shareWebPage":"'+shareWebPage+'","shareWay":"'+shareWay+'"}}';
	},
	appurlOpen:function(operation,data,type){
		var url='yimay://app?content=',
		content_obj={"TYPE":(type?type:"JIUXIU"),"OPERATION":operation,"DATA":data};
		//$('body').html(url+JSON.stringify(content_obj));
		window.location=url+JSON.stringify(content_obj);
	},
	urlOpen:function(url){
		window.location=_wap_config.linkUrl+url;
	},
    openApp:function(appurl) {
    	var openapptimer=null,userAgent=navigator.userAgent.toLowerCase(),defaulturl='http://www.jiuxiulvxing.com/d/'+this.__jx_getCh();
      	window.location=appurl;
      	// 部分浏览器只支持 vendor-prefixed
		// 根据浏览器支持情况设置隐藏属性和可见状态改变事件
		var hidden, state, visibilityChange;
		if (typeof document.hidden !== "undefined") {
		  hidden = "hidden";
		  visibilityChange = "visibilitychange";
		  state = "visibilityState";
		} else if (typeof document.mozHidden !== "undefined") {
		  hidden = "mozHidden";
		  visibilityChange = "mozvisibilitychange";
		  state = "mozVisibilityState";
		} else if (typeof document.msHidden !== "undefined") {
		  hidden = "msHidden";
		  visibilityChange = "msvisibilitychange";
		  state = "msVisibilityState";
		} else if (typeof document.webkitHidden !== "undefined") {
		  hidden = "webkitHidden";
		  visibilityChange = "webkitvisibilitychange";
		  state = "webkitVisibilityState";
		}
		 
		// 添加一个时间来实时改变页面的标题
		document.addEventListener(visibilityChange, function(e) {
			clearTimeout(openapptimer);
			//$('.link_app').text('有app我不会打开应用宝的');
		}, false);
		openapptimer=setTimeout(function(){
			window.location=defaulturl;
			//$('.link_app').text('没有装app那我打开应用宝啦');
		}, 2000);
    },
	is_injxapp : function(){
		return ua.match(/JiuXiuLvXing/i) == 'jiuxiulvxing';
	},
	is_wxbrowser : function(){
		return ua.match(/MicroMessenger/i) == 'micromessenger';
	},
	is_weibobrowser : function(){
		return ua.match(/WeiBo/i) == 'weibo';
	},
	is_qqbrowser : function(){
		return ua.match(/QQ/i) == 'qq';
	},
	isNull : function(obj) {
		if(typeof obj == "object"){
			for ( var name in obj ) {
				return false;
			}
			return true;
		}
		return null == obj || typeof obj == "undefined" || "" == obj || obj.length == 0;
	},
	getAppVersionCode : function(){
		var version = "";
		if(ua.match(/jiuxiulvxing_(.*);/)){
          	version=ua.match(/jiuxiulvxing_(.*);/)[1];
        }
        return version;
	},
	getAppChannel : function(){
        var channal='';
        if(ua.match(/channal_(.*)/)){
          	 channal=ua.match(/channal_(.*)/)[1];
        }
	    return channal;
	},
	/**
	 *获取渠道
	 */
	__jx_getCh:function() {
		
		var ch = this.getCookie("jx_ch");
		if (!this.isNull(ch)) {
			return ch;
		}
		if (this.is_injxapp()) {
			return _wap_config.ch.jxapp;
		}
		if (this.is_wxbrowser()) {
			return _wap_config.ch.weixin;
		}
		return _wap_config.ch.jxwap;
	},
	__jx_getAId:function() {

		if (this.is_wxbrowser()) {
			return _wap_config.aid_wx;
		}
		if (this.is_injxapp()) {
			return _wap_config.aid_app;
		}
		return _wap_config.aid;
	},
	getUid : function(){
		if(!this.getCookie("_uid")){
			return "";
		}
		return this.getCookie("_uid");
	},
	getTk : function(){
		if(!this.getCookie("_wtk")){
			return "";
		}
		return this.getCookie("_wtk");
	},
	getAppwaptk : function(){
		if(!this.getCookie("_app_wap_tk")){
			return "";
		}
		return this.getCookie("_app_wap_tk");
	},
	html_encode : function(str){   
	  var s = "";   
	  if (str.length == 0) return "";   
	  s = str.replace(/&/g, "&amp;");   
	  s = s.replace(/</g, "&lt;");   
	  s = s.replace(/>/g, "&gt;");   
	  s = s.replace(/ /g, "&nbsp;");   
	  s = s.replace(/\'/g, "&#39;");   
	  s = s.replace(/\"/g, "&quot;");   
	  s = s.replace(/\n|\r\n/g, "<br>");  
	  return s;   
	},
	html_decode : function(str){
	  var s = "";   
	  if (str.length == 0) return "";   
	  s = str.replace(/&amp;/g, "&");   
	  s = s.replace(/&lt;/g, "<");   
	  s = s.replace(/&gt;/g, ">");   
	  s = s.replace(/&nbsp;/g, " ");   
	  s = s.replace(/&#39;/g, "\'");   
	  s = s.replace(/&quot;/g, "\"");   
	  s = s.replace(/<br>/g, "\n");   
	  return s; 
	}
}